package com.banfeiguanli.springboot.service;

import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.common.Result;
import com.banfeiguanli.springboot.entity.ExpenseApply;
import com.banfeiguanli.springboot.entity.PaymentProject;
import com.banfeiguanli.springboot.entity.dto.ExpenseApplyDTO;
import com.banfeiguanli.springboot.entity.dto.PaymentProjectDTO;
import com.banfeiguanli.springboot.mapper.ClassExpenseMapper;
import com.banfeiguanli.springboot.mapper.PaymentProjectMapper;
import com.banfeiguanli.springboot.mapper.UserMapper;
import com.banfeiguanli.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PaymentProjectService {
    @Autowired
    private PaymentProjectMapper paymentProjectMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassService classService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClassAdminService classAdminService;
    @Autowired
    private ClassExpenseMapper classExpenseMapper;

    //获取班级缴费项目(班级管理员)
    public Result getClassPaymentProject(String token,
                                         Integer pageNumber,
                                         Integer pageSize,
                                         String searchTitle) {
        Map<String, Object> data = new HashMap<>();
        //用户ID
        int userID = TokenUtils.getIdByToken(token);
        if (!classService.isIntoClass(userID)) {
            return Result.error(Constant.CODE_612, "未加入班级！");
        }
        //
        pageNumber = (pageNumber - 1) * pageSize;
        //查询
        List<PaymentProject> paymentProjects = paymentProjectMapper.getClassPaymentProject(userID, pageNumber, pageSize, searchTitle);
        data.put("paymentProjects", paymentProjects);
        //获取缴费项目总数量
        Integer paymentProjectTotal = paymentProjectMapper.countPaymentProjectTotal(userID, searchTitle);
        data.put("paymentProjectTotal", paymentProjectTotal);
        return Result.success(data);
    }

    //获取班级缴费项目(用户)
    public Result getClassPaymentProjectForUser(String token,
                                                Integer pageNumber,
                                                Integer pageSize,
                                                String searchTitle) {
        Map<String, Object> data = new HashMap<>();
        //用户ID
        int userID = TokenUtils.getIdByToken(token);
        if (!classService.isIntoClass(userID)) {
            return Result.error(Constant.CODE_612, "未加入班级！");
        }
        //
        pageNumber = (pageNumber - 1) * pageSize;
        //查询
        List<PaymentProject> paymentProjects = paymentProjectMapper.getClassPaymentProjectForUser(userID, pageNumber, pageSize, searchTitle);
        data.put("paymentProjects", paymentProjects);
        //获取缴费项目总数量
        Integer paymentProjectTotal = paymentProjectMapper.countPaymentProjectTotalForUser(userID, searchTitle);
        data.put("paymentProjectTotal", paymentProjectTotal);
        return Result.success(data);
    }

    //删除缴费项目
    public Result deleteClassPaymentProject(PaymentProjectDTO paymentProjectDTO) {
        Map<String, Object> data = new HashMap<>();
        //班级管理员ID
        int userID = TokenUtils.getIdByToken(paymentProjectDTO.getToken());
        //班级管理员所在班级ID
        Integer classID = userMapper.getUserClassInfo(userID).get(0).getClassID();
        //要删除的项目ID
        Integer payProjID = paymentProjectDTO.getPayProjID();
        if (payProjID == null) {
            return Result.error(Constant.CODE_640, "项目不存在！");
        }
        //要删除的项目的班级ID
        Integer payProjClassID = paymentProjectMapper.getPaymentProjectInfo(payProjID).get(0).getClassID();
        if (classID != payProjClassID) {
            return Result.error(Constant.CODE_641, "无权删除其他班级的项目");
        }
        //校验无问题，删除项目(假删)
        Integer changeRow = paymentProjectMapper.deleteProject(payProjID);
        return Result.success(Constant.CODE_200, "删除成功");
    }

    //发布缴费项目
    public Result createPaymentProject(PaymentProjectDTO paymentProjectDTO) {
        Map<String, Object> data = new HashMap<>();
        //班级管理员的userID
        int userID = TokenUtils.getIdByToken(paymentProjectDTO.getToken());
        //判断是否是班级管理员
        if (!userService.userIsClassAdmin(userID)) {
            return Result.error(Constant.CODE_620, "非班级管理员！");
        }
        if ((paymentProjectDTO.getPayProjAmount() == null) ||
                (paymentProjectDTO.getPayProjAmount() < 0)) {
            return Result.error(Constant.CODE_642, "缴费金额非法！");
        }
        //班级管理员ID
        Integer classAdminID = classAdminService.getClassAdmin(userID).getClassAdminID();
        //结束时间
        Timestamp releaseTime = new Timestamp(System.currentTimeMillis());
        long durationDay = releaseTime.getTime() + (long) 1000 * 3600 * 24 * paymentProjectDTO.getDurationDay();
        Timestamp deadLine = new Timestamp(durationDay);
        //插入数据
        Integer changeRow = paymentProjectMapper.createPaymentProject(classAdminID,
                paymentProjectDTO.getPayProjTitle(),
                paymentProjectDTO.getPayProjBrief(),
                paymentProjectDTO.getPayProjAmount(),
                releaseTime,
                deadLine);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_643, "发布缴费项目失败");
        }
        //
        data.put("changeRow", changeRow);
        return Result.success("发布成功", data);
    }

    public Result pay(String token, Integer paymentProjectID) {
        Map<String, Object> data = new HashMap<>();
        //用户ID
        int userID = TokenUtils.getIdByToken(token);
        //班费当前金额
        float classExp = paymentProjectMapper.getClassExpense(userID);
        //
        Integer changeRow = paymentProjectMapper.pay(userID, paymentProjectID, classExp);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_644, "缴费失败！");
        }
        //缴费成功，修改班费
        changeRow = paymentProjectMapper.updateClassExpense(userID, paymentProjectID);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_645, "更新班费余额失败！");
        }
        return Result.success("缴费成功！", changeRow);
    }


    //获取班级缴费项目(班级管理员)
    public Result getExpenseApply(String token,
                                  Integer applyMessagePageNumber,
                                  Integer applyMessagePageSize,
                                  String searchExpenseApplyReason) {
        Map<String, Object> data = new HashMap<>();
        //用户ID
        int userID = TokenUtils.getIdByToken(token);
        if (!classService.isIntoClass(userID)) {
            return Result.error(Constant.CODE_612, "未加入班级！");
        }
        applyMessagePageNumber = (applyMessagePageNumber - 1) * applyMessagePageSize;
        //查询
        List<ExpenseApply> ExpenseApplys = paymentProjectMapper.getExpenseApply(userID, applyMessagePageNumber, applyMessagePageSize, searchExpenseApplyReason);
        data.put("ExpenseApplys", ExpenseApplys);
        //获取缴费项目总数量
        Integer ExpenseApplyTotal = paymentProjectMapper.getExpenseApplyTotal(userID, searchExpenseApplyReason);
        data.put("ExpenseApplyTotal", ExpenseApplyTotal);
        return Result.success(data);
    }


    //拒绝申请班费
    public Result refuseExpenseApply(ExpenseApplyDTO expenseApplyDTO) {
        //班级管理员ID
        int userID = TokenUtils.getIdByToken(expenseApplyDTO.getToken());

        //用户班级管理员ID
        int classAdminID = paymentProjectMapper.getClassAdminID(userID);
        //班费申请ID
        int expApplyID = expenseApplyDTO.getExpApplyID();
        //拒绝班费申请
        Integer auditRow = paymentProjectMapper.refuseExpenseApply(classAdminID, expApplyID);

        if (auditRow != 1) {
            return Result.error(Constant.CODE_500, "操作失败！");
        }

        return Result.success(Constant.CODE_200, "操作成功！");
    }

    //同意班费申请
    public Result approveExpenseApply(ExpenseApplyDTO expenseApplyDTO) {
        //班级管理员ID
        int userID = TokenUtils.getIdByToken(expenseApplyDTO.getToken());

        //用户班级管理员ID
        int classAdminID = paymentProjectMapper.getClassAdminID(userID);
        //班费申请ID
        int expApplyID = expenseApplyDTO.getExpApplyID();
        //班费余额
        Float balance = classExpenseMapper.getClassExpense(userID);
        if (balance < (expenseApplyDTO.getApplyAmount() * (-1))) {
            return Result.error(Constant.CODE_501, "班费余额小于申请的金额!");
        }
        //同意班费申请
        Integer auditRow = paymentProjectMapper.approveExpenseApply(classAdminID, expApplyID, balance);
        if (auditRow != 1) {
            return Result.error(Constant.CODE_500, "操作失败！");
        }
        //更新班费余额
        Integer updateRow = paymentProjectMapper.updateClassExpenseForApply(userID, expApplyID);
        if (updateRow != 1) {
            return Result.error(Constant.CODE_500, "操作失败！");
        }
        return Result.success("操作成功！", null);
    }
}
